package com.iwm.qa.mdm.view;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.iwm.qa.mdm.R;
import com.iwm.qa.mdm.adapter.BorrowRecyclerAdapter;
import com.iwm.qa.mdm.config.ApiConfig;
import com.iwm.qa.mdm.http.OkHttp;
import com.iwm.qa.mdm.model.Borrow;

import java.io.IOException;

import okhttp3.Request;

public class RecyclerViewFragment extends Fragment {

    private Borrow borrowBean;
    private BorrowRecyclerAdapter mBorrowRecyclerAdapter;
    private RecyclerView recyclerView;

    public static RecyclerViewFragment newInstance() {
        return new RecyclerViewFragment();
    }

    public RecyclerViewFragment() {
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.recyclerview_fragment, container, false);
        findViews(view);
        setRecyclerView();
        setOkHttp();
        return view;
    }

    public void setOkHttp() {
        OkHttp.getAsync(ApiConfig.GET_ALL_AVAILABLE_DEVICE, new OkHttp.DataCallBack() {
            @Override
            public void requestFailure(Request request, IOException e) {

            }

            @Override
            public void requestSuccess(String result) throws Exception {
                Gson gson = new Gson();
                borrowBean = gson.fromJson(result, Borrow.class);
                if (mBorrowRecyclerAdapter != null) {
                    mBorrowRecyclerAdapter.setData(borrowBean);
                }
            }
        });
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    private void findViews(View view) {
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
    }

    private void setRecyclerView() {
        recyclerView.setHasFixedSize(true);
        LinearLayoutManager llm = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(llm);

        mBorrowRecyclerAdapter = new BorrowRecyclerAdapter(RecyclerViewFragment.this);
        recyclerView.setAdapter(mBorrowRecyclerAdapter);
    }

}